package com.kanshu.ksgb.fastread.doudou.module.download.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.BookBussinessService;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.DownLoadChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.DownloadRequestParams;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DownloadProgressEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.retrofit.DownloadChapterService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 下载章节后台服务
 * Created by wcy on 2017\7\6 0006.
 */
public class DownloadBookService extends Service {
    // 队列中最大数目
    public static final int MAX_QUEUE_ITEM_NUM = 1;
    // 所有下载任务是否被取消
    public static boolean sCancel;
    public static boolean sStartService;
    private boolean isBusy;
    private DownloadRequestParams mRequestParams = new DownloadRequestParams();
    private RetrofitHelper mHelper = RetrofitHelper.getInstance();
    DownloadChapterService mBookService;
    private static List<DownLoadChapterBean> sDownLoadQueue = new ArrayList<>();
    // 书籍下载任务中  总章节数
    private static Map<String, Integer> sDownloadSumCount = new HashMap<>();
    // 书籍下载任务中  当前下载章节数
    private static Map<String, Integer> sCurrentDownloadCount = new HashMap<>();
    static String sCurrentGroupId = "";
    static String sCurrentBookId = "";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public static void post(Object object) {
        EventBus.getDefault().post(object);
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, DownloadBookService.class);
        context.startService(intent);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mBookService == null) {
            mBookService = mHelper.createService(DownloadChapterService.class);
        }
        return START_REDELIVER_INTENT;
    }

    /**
     * 是否存在下载队列中
     * @param groupId
     * @return
     */
    public static boolean isExistQueue(String groupId) {
        for (DownLoadChapterBean downLoadItem : sDownLoadQueue) {
            if (TextUtils.equals(downLoadItem.id, groupId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前队列中正在下载的分组groupId
     * @return
     */
    public static String getCurrentGroupId() {
        return sCurrentGroupId;
    }

    /**
     * 获取当前队列中正在下载的bookId
     * @return
     */
    public static String getCurrentBookId() {
        return sCurrentBookId;
    }

    /**
     * 判断书籍是否有在下载任务队列中
     * @return
     */
    public static boolean isBookIdDownload(String bookId) {
        for (DownLoadChapterBean downLoadItem : sDownLoadQueue) {
            if (!Utils.isEmptyList(downLoadItem.chapters) && TextUtils.equals(downLoadItem.book_id, bookId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取书籍下载进度
     * @return
     */
    public static int[] getCurrentProgress(String bookId) {
        int[] result = new int[2];
        result[0] = sDownloadSumCount.get(bookId);
        result[1] = sCurrentDownloadCount.get(bookId);
        return result;
    }

    /**
     * 重置书籍下载进度
     * @return
     */
    public static void reSetCurrentProgress(String bookId) {
        sDownloadSumCount.put(bookId, 0);
        sCurrentDownloadCount.put(bookId, 0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleAddToQueue(DownLoadChapterBean item) {
        if (sCancel) {
            return;
        }
        if (sDownLoadQueue.size() < MAX_QUEUE_ITEM_NUM) {
            isBusy = false;
        }
        // bookid为空说明是为了触发下载任务
        if (TextUtils.isEmpty(item.book_id) && TextUtils.isEmpty(item.id)) {
            if (sDownLoadQueue.size() > 0) {
                downloadGroup(sDownLoadQueue.get(0));
            }
        } else {
            // 判断是否在队列中
            for (DownLoadChapterBean downLoadItem : sDownLoadQueue) {
                if (TextUtils.equals(downLoadItem.id, item.id)) {
                    return;
                }
            }
            // 加入队列中
            sDownLoadQueue.add(item);
            // 设置下载章节数量
            sCurrentDownloadCount.put(item.book_id, sCurrentDownloadCount.get(item.book_id) + item.chapters.size());
            if (sDownLoadQueue.size() > MAX_QUEUE_ITEM_NUM) {
                isBusy = true;
            }
            // 告知正在等待中
            if (!isBusy) {
                // 先获取所有章节信息
                ARouter.getInstance().navigation(BookBussinessService.class).getAllSimpleChapters(item.book_id);
                downloadGroup(item);
            }
        }
    }

    /**
     * 下载一个分组
     * @param item
     */
    @SuppressLint("StaticFieldLeak")
    public void downloadGroup(final DownLoadChapterBean item) {
        if (Utils.isEmptyList(item.chapters)) {
            return;
        }
        new AsyncTask<Void, Void, Integer>() {

            @Override
            protected Integer doInBackground(Void... params) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int failCount = 0;
                sCurrentGroupId = item.id;
                sCurrentBookId = item.book_id;
                // 网络异常，取消下载
                if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
                    item.isCancel = true;
                }
                for (DownLoadChapterBean chapterBean : item.chapters) {
                    if (sCancel || chapterBean == null) {
                        break;
                    }
                    // 开始下载
                    if (!item.isFinish) {
                        if (CacheManager.getInstance().getDownloadChapterFile(chapterBean.book_id, chapterBean.order) == null) {
                            if(item.isCancel){ // 取消下载 直接保存失败信息
                                saveDownloadFail(item, chapterBean);
                            } else {
                                boolean result = downloadOneChapter(item, chapterBean);
                                // 保存下载进度
                                sDownloadSumCount.put(item.book_id, sDownloadSumCount.get(item.book_id) + 1);
                                if (!result) {
                                    failCount++;
                                    saveDownloadFail(item, chapterBean);
                                } else {
                                    downLoadSuccDeleteInfo(item, chapterBean);
                                }
                            }
                            Log.d("download", "downloading :" + chapterBean.order);
                            post(new DownloadProgressEvent(chapterBean.book_id, item.book_title, false));
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            post(new DownloadProgressEvent(item.book_id, item.book_title, false));
                        }
                    }
                }
                return failCount;
            }

            @Override
            protected void onPostExecute(Integer failureCount) {
                super.onPostExecute(failureCount);
                item.isFinish = true;
                // 下载完成，从队列里移除
                sCurrentBookId = "";
                sCurrentGroupId = "";
                sDownLoadQueue.remove(item);

                // 统计本书下载章节数量 保存至MMKV
                int downloadCount = CacheManager.getInstance().getBookDownloadNum(item.book_id);
                MMKVUserManager.getInstance().saveBookDownloadChapterCount(item.book_id, downloadCount);

                // 每组 完成通知
                post(new DownloadProgressEvent(item.book_id, item.book_title, true));
                if (!sCancel) {
                    if(!isBookIdDownload(item.book_id)){ // 书籍没有下载任务在队列中了
                        // 书籍下载完成重置进度
                        reSetCurrentProgress(item.book_id);
                        String failChapter = MMKVUserManager.getInstance().getDownLoadFailGroupId(item.book_id);
                        if(failChapter.length() < Constants.DOWNLOAD_FAILINFO_DEFAULT_LENGTH){ // 没有下载失败章节，提示下载成功
                            ToastUtil.showStaticMessage("《" + item.book_title + "》下载成功");
                        } else { // 有下载失败章节，提示用户需重新下载
                            String because = MMKVUserManager.getInstance().getDownLoadFailBecause(item.book_id);
                            ToastUtil.showStaticMessage(because + (because.startsWith("网络中断") ? "" : "，请重新下载"));
                        }
                    }
                    // post一个空事件，通知继续执行下一个任务
                    post(new DownLoadChapterBean());
                } else {
                    sDownLoadQueue.clear();
                }
                sCancel = false;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }


    /**
     * 保存失败记录
     */
    public void saveDownloadFail(DownLoadChapterBean item, DownLoadChapterBean chapterBean){
        MMKVUserManager.getInstance().saveDownLoadFailGroupId(item.book_id, item.id, item.book_title);
        MMKVUserManager.getInstance().saveDownLoadFailChapter(item.book_id, item.id, chapterBean.content_id, chapterBean.order);
    }

    public void downLoadSuccDeleteInfo(DownLoadChapterBean item, DownLoadChapterBean chapterBean){
        MMKVUserManager.getInstance().downLoadSuccDeleteChapter(item.book_id, item.id, item.book_title, chapterBean.content_id, chapterBean.order);
    }


    /**
     * 下载一章节
     */
    public boolean downloadOneChapter(DownLoadChapterBean item, DownLoadChapterBean bean) {
        mRequestParams.content_id = bean.content_id;
        mRequestParams.book_id = bean.book_id;
        mRequestParams.is_cache = DownloadRequestParams.CACHED;
        try {
            Response<ResponseBody> execute = mBookService.downChapterContent(mRequestParams).execute();
            if (execute != null) {
                String s = execute.body().string();
                JSONObject object = new JSONObject(s);
                JSONObject result = object.getJSONObject("result");
                JSONObject status = result.getJSONObject ("status");
                int code = status.getInt("code");
                String str = status.getString("msg");
                if (code != 0) {
                    if(code == Constants.ErrCode.Offline){ // 书籍下架
                        MMKVUserManager.getInstance().saveDownLoadFailBecause(item.book_id, "书籍已下架，无法下载");
                    }
                    return false;
                }
                JSONObject data = result.getJSONObject("data");
                ChapterBean chapterBean = JsonUtils.json2BeanByFastJson(data.toString(), ChapterBean.class);
                if (chapterBean != null && !TextUtils.isEmpty(chapterBean.content)) {
                    boolean mIsCanCacheByServer = chapterBean.is_can_cache == 1;
                    CacheManager.getInstance().setCanCache(mIsCanCacheByServer);
                    CacheManager.getInstance().saveDownloadChapterFile(item.book_id, bean.order, chapterBean.content);
                    // 保存简单章节信息
                    SettingManager.getInstance().saveSimpleChapterInfo(chapterBean.book_id, Integer.parseInt(chapterBean.order), chapterBean);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        sStartService = true;
        EventBus.getDefault().register(this);
    }
    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        sStartService = false;
        super.onDestroy();
    }

    /**
     * 清除下载队列数据
     */
    public static void clearAll() {
        sDownLoadQueue.clear();
        sCancel = true;
    }

    /**
     * 检查service是否存活 存活的话再发通知
     * @param context
     * @param event
     */
    public static void checkServiceAndPostEvent(Context context, DownLoadChapterBean event) {
        sCancel = false;
        if (!sStartService) {
            DownloadBookService.actionStart(context);
            AndroidSchedulers.mainThread().scheduleDirect(() -> post(event), 500, TimeUnit.MILLISECONDS);
        } else {
            post(event);
        }

    }
}
